package com.xywh.micro_warehousing.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xw.repo.XEditText;
import com.xywh.micro_warehousing.R;
import com.xywh.micro_warehousing.di.component.DaggerTab3Component;
import com.xywh.micro_warehousing.di.module.Tab3Module;
import com.xywh.micro_warehousing.mvp.contract.Tab3Contract;
import com.xywh.micro_warehousing.mvp.presenter.Tab3Presenter;
import com.xywh.micro_warehousing.mvp.ui.adapter.Tab3Adapter;
import com.xywh.micro_warehousing.mvp.ui.entity.Tab3;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.DateTimePicker;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab3Fragment extends BaseFragment<Tab3Presenter> implements Tab3Contract.View, OnRefreshListener {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.xet_search)
    XEditText xetSearch;
    @BindView(R.id.btn_search)
    Button btnSearch;
    private Tab3Adapter mAdapter;
    private List<Tab3> mDataBeanList = new ArrayList<>();
    private String mStartTime = "";
    private String mEndTime = "";

    public static Tab3Fragment newInstance() {
        Tab3Fragment fragment = new Tab3Fragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab3Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab3Module(new Tab3Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab3, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
        ToolbarUtils.initToolbarTitleNoBack(view, this, "出入库记录");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        //getTab3Data();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
//        mEmptyLayout.setVisibility(View.GONE);
//        mDataBeanList.add(new Tab3.DataBean(R.drawable.icon_return, "照明灯", "RF9120", "物资归还", "今天 14:20", "+1"));
//        mDataBeanList.add(new Tab3.DataBean(R.drawable.icon_return, "电源插件", "RF9562", "物资归还", "昨天10:20", "+1"));
//        mDataBeanList.add(new Tab3.DataBean(R.drawable.icon_picking, "熔断器", "RF9552", "物资领用", "昨天10:20", "-1"));
//        mDataBeanList.add(new Tab3.DataBean(R.drawable.icon_picking, "熔断器", "RF9552", "物资领用", "019-10-10   10:20", "-1"));
//        mDataBeanList.add(new Tab3.DataBean(R.drawable.icon_picking, "保护插件", "RF9524", "物资归还", "2019-10-05   11:20", "-1"));
//        mDataBeanList.add(new Tab3.DataBean(R.drawable.icon_storage, "熔断器", "RF9120", "物资入库", "2019-09-05   14:20", "+5"));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new Tab3Adapter(getActivity(), mDataBeanList));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mDataBeanList.get(position).getId());
                if (mDataBeanList.get(position).getInouttype().equals("0")) {//领用
                    Utils.navigation(getActivity(), RouterHub.ACTIVITY_PICKING_DETAILS, bundle);
                } else if (mDataBeanList.get(position).getInouttype().equals("1")) {//返还
                    Utils.navigation(getActivity(), RouterHub.ACTIVITY_RETURN_DETAILS, bundle);

                }
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void getTab3DataSuccess(List<Tab3> entityData) {

        if (entityData != null && entityData.size() > 0) {
            mDataBeanList.clear();
            mDataBeanList.addAll(entityData);
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//
//        mRefreshLayout.finishRefresh();
//        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(getActivity());
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getActivity(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @OnClick({R.id.tv_start_time, R.id.tv_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                onYearMonthDayTimePicker(tvStartTime, 0);
                break;
            case R.id.tv_end_time:
                onYearMonthDayTimePicker(tvEndTime, 1);
                break;
        }
    }

    public void onYearMonthDayTimePicker(TextView view, int isStartOrEnd) {

        DateTimePicker picker = new DateTimePicker(getActivity(), DateTimePicker.HOUR_24);

        Calendar now = Calendar.getInstance();

        picker.setCancelText("取消");
        picker.setSubmitText("确定");
        picker.setActionButtonTop(true);
        picker.setDateRangeStart(1900, 1, 1);
        picker.setDateRangeEnd(2500, 12, 31);
        picker.setSelectedItem(now.get(Calendar.YEAR), (now.get(Calendar.MONTH) + 1), now.get(Calendar.DAY_OF_MONTH), now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE));
        picker.setTimeRangeStart(0, 0);
        picker.setTimeRangeEnd(23, 59);
        picker.setCanLinkage(false);
        picker.setTitleText("请选择");
//        picker.setStepMinute(5);
        picker.setWeightEnable(true);
        picker.setWheelModeEnable(true);
        LineConfig config = new LineConfig();
        config.setColor(Color.BLACK);//线颜色
        config.setAlpha(120);//线透明度
        config.setVisible(true);//线不显示 默认显示
        picker.setLineConfig(config);
        picker.setLabel("年", "月", "日", "时", "分");
        picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() {
            @Override
            public void onDateTimePicked(String year, String month, String day, String hour, String minute) {
//                ArmsUtils.snackbarText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
                view.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":00");
                if (isStartOrEnd == 0) {
                    mStartTime = view.getText().toString().trim();
                } else if (isStartOrEnd == 1) {
                    mEndTime = view.getText().toString().trim();
                }
            }
        });
        picker.show();

    }

    @OnClick(R.id.btn_search)
    public void onViewClicked() {

//        if (TextUtils.isEmpty(mStartTime)) {
//            showMessage("请选择开始时间");
//            onYearMonthDayTimePicker(tvStartTime, 0);
//            return;
//        }
//        if (TextUtils.isEmpty(mEndTime)) {
//            showMessage("请选择结束时间");
//            onYearMonthDayTimePicker(tvEndTime, 1);
//            return;
//        }
//        if (TextUtils.isEmpty(getXetSearch())) {
//            showMessage("请输入物资描述");
//            return;
//        }
        getTab3Data();
    }

    private void getTab3Data() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        map.put("startTime", mStartTime);
        map.put("endTime", mEndTime);
        map.put("material", getXetSearch());
        mPresenter.getTab3Data(map);
    }

    @NotNull
    private String getXetSearch() {
        return xetSearch.getText().toString().trim();
    }
}
